{{define "content"}}
<div x-data="pushStatsData()" class="space-y-6">
    <!-- Page Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">推送统计</h1>
            <p class="mt-1 text-sm text-gray-500">查看推送数据统计和分析报告，了解推送效果和趋势。</p>
        </div>
        <div class="mt-4 sm:mt-0 flex space-x-3">
            <a href="/push" 
               class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500">
                <i class="fas fa-arrow-left mr-2"></i>
                返回推送管理
            </a>
            <button @click="refreshStats()" 
                    :disabled="loading"
                    class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50">
                <i class="fas fa-sync-alt mr-2" :class="loading ? 'animate-spin' : ''"></i>
                刷新数据
            </button>
        </div>
    </div>

    <!-- Date Range Filter -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">统计时间范围</h3>
        </div>
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
                    <input type="date" 
                           x-model="dateRange.startDate"
                           @change="loadStats()"
                           class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
                    <input type="date" 
                           x-model="dateRange.endDate"
                           @change="loadStats()"
                           class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                </div>
                <div class="flex items-end">
                    <div class="flex space-x-2">
                        <button @click="setQuickRange('today')" 
                                :class="isQuickRangeActive('today') ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 border-gray-300'"
                                class="px-3 py-2 border rounded-md text-sm font-medium hover:bg-blue-50">
                            今天
                        </button>
                        <button @click="setQuickRange('week')" 
                                :class="isQuickRangeActive('week') ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 border-gray-300'"
                                class="px-3 py-2 border rounded-md text-sm font-medium hover:bg-blue-50">
                            本周
                        </button>
                        <button @click="setQuickRange('month')" 
                                :class="isQuickRangeActive('month') ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 border-gray-300'"
                                class="px-3 py-2 border rounded-md text-sm font-medium hover:bg-blue-50">
                            本月
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Overview Stats -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <!-- Total Pushes -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-paper-plane text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">总推送数</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.total || 0"></dd>
                        </dl>
                    </div>
                </div>
            </div>
        </div>

        <!-- Success Rate -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-check-circle text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">成功率</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="(stats.successRate || 0) + '%'"></dd>
                        </dl>
                    </div>
                </div>
            </div>
        </div>

        <!-- Success Count -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-thumbs-up text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">成功推送</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.success || 0"></dd>
                        </dl>
                    </div>
                </div>
            </div>
        </div>

        <!-- Failed Count -->
        <div class="bg-white overflow-hidden shadow rounded-lg">
            <div class="p-5">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-red-500 rounded-md flex items-center justify-center">
                            <i class="fas fa-exclamation-triangle text-white"></i>
                        </div>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">失败推送</dt>
                            <dd class="text-lg font-medium text-gray-900" x-text="stats.failed || 0"></dd>
                        </dl>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Push Type Distribution -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">推送类型分布</h3>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <template x-for="(item, type) in stats.byType" :key="type">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <div class="w-4 h-4 rounded-full mr-3"
                                     :class="{
                                         'bg-blue-500': type === 'smart',
                                         'bg-green-500': type === 'manual',
                                         'bg-purple-500': type === 'batch'
                                     }"></div>
                                <span class="text-sm font-medium text-gray-900"
                                      x-text="{
                                          'manual': '手动推送'
                                      }[type] || type"></span>
                            </div>
                            <div class="flex items-center space-x-4">
                                <span class="text-sm text-gray-500" x-text="item.count + ' 次'"></span>
                                <div class="w-24 bg-gray-200 rounded-full h-2">
                                    <div class="h-2 rounded-full"
                                         :class="{
                                             'bg-blue-500': type === 'smart',
                                             'bg-green-500': type === 'manual',
                                             'bg-purple-500': type === 'batch'
                                         }"
                                         :style="`width: ${stats.total > 0 ? (item.count / stats.total * 100) : 0}%`"></div>
                                </div>
                                <span class="text-sm font-medium text-gray-900" 
                                      x-text="stats.total > 0 ? Math.round(item.count / stats.total * 100) + '%' : '0%'"></span>
                            </div>
                        </div>
                    </template>
                    
                    <!-- Empty State -->
                    <div class="text-center py-8" x-show="Object.keys(stats.byType || {}).length === 0">
                        <i class="fas fa-chart-pie text-4xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">暂无推送类型数据</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Status Distribution -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">推送状态分布</h3>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <template x-for="(item, status) in stats.byStatus" :key="status">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <div class="w-4 h-4 rounded-full mr-3"
                                     :class="{
                                         'bg-yellow-500': status === 'pending',
                                         'bg-green-500': status === 'success',
                                         'bg-red-500': status === 'failed'
                                     }"></div>
                                <span class="text-sm font-medium text-gray-900"
                                      x-text="{
                                          'pending': '待处理',
                                          'success': '成功',
                                          'failed': '失败'
                                      }[status] || status"></span>
                            </div>
                            <div class="flex items-center space-x-4">
                                <span class="text-sm text-gray-500" x-text="item.count + ' 次'"></span>
                                <div class="w-24 bg-gray-200 rounded-full h-2">
                                    <div class="h-2 rounded-full"
                                         :class="{
                                             'bg-yellow-500': status === 'pending',
                                             'bg-green-500': status === 'success',
                                             'bg-red-500': status === 'failed'
                                         }"
                                         :style="`width: ${stats.total > 0 ? (item.count / stats.total * 100) : 0}%`"></div>
                                </div>
                                <span class="text-sm font-medium text-gray-900" 
                                      x-text="stats.total > 0 ? Math.round(item.count / stats.total * 100) + '%' : '0%'"></span>
                            </div>
                        </div>
                    </template>
                    
                    <!-- Empty State -->
                    <div class="text-center py-8" x-show="Object.keys(stats.byStatus || {}).length === 0">
                        <i class="fas fa-chart-bar text-4xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">暂无推送状态数据</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Daily Trend Chart -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">推送趋势</h3>
        </div>
        <div class="p-6">
            <div class="space-y-4" x-show="stats.dailyTrend && stats.dailyTrend.length > 0">
                <div class="overflow-x-auto">
                    <div class="flex items-end space-x-2 h-64 min-w-full">
                        <template x-for="day in stats.dailyTrend" :key="day.date">
                            <div class="flex flex-col items-center flex-1 min-w-0">
                                <div class="flex flex-col items-center space-y-1 h-48">
                                    <!-- Success Bar -->
                                    <div class="w-8 bg-green-500 rounded-t" 
                                         :style="`height: ${getBarHeight(day.success, getMaxDailyCount())}px`"
                                         :title="`成功: ${day.success}`"></div>
                                    <!-- Failed Bar -->
                                    <div class="w-8 bg-red-500" 
                                         :style="`height: ${getBarHeight(day.failed, getMaxDailyCount())}px`"
                                         :title="`失败: ${day.failed}`"></div>
                                    <!-- Pending Bar -->
                                    <div class="w-8 bg-yellow-500 rounded-b" 
                                         :style="`height: ${getBarHeight(day.pending, getMaxDailyCount())}px`"
                                         :title="`待处理: ${day.pending}`"></div>
                                </div>
                                <div class="text-xs text-gray-500 mt-2 text-center">
                                    <div x-text="formatDate(day.date)"></div>
                                    <div class="font-medium" x-text="day.total"></div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
                
                <!-- Legend -->
                <div class="flex justify-center space-x-6 mt-4">
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-green-500 rounded mr-2"></div>
                        <span class="text-sm text-gray-600">成功</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-red-500 rounded mr-2"></div>
                        <span class="text-sm text-gray-600">失败</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-yellow-500 rounded mr-2"></div>
                        <span class="text-sm text-gray-600">待处理</span>
                    </div>
                </div>
            </div>
            
            <!-- Empty State -->
            <div class="text-center py-12" x-show="!stats.dailyTrend || stats.dailyTrend.length === 0">
                <i class="fas fa-chart-line text-4xl text-gray-400 mb-4"></i>
                <h4 class="text-lg font-medium text-gray-900 mb-2">暂无趋势数据</h4>
                <p class="text-gray-500">选择时间范围查看推送趋势</p>
            </div>
        </div>
    </div>

    <!-- Top Partners -->
    <div class="bg-white shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">热门合作机构</h3>
        </div>
        <div class="p-6">
            <div class="space-y-4" x-show="stats.topPartners && stats.topPartners.length > 0">
                <template x-for="(partner, index) in stats.topPartners" :key="partner.id">
                    <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white font-medium text-sm"
                                 x-text="index + 1"></div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900" x-text="partner.name"></div>
                                <div class="text-sm text-gray-500">
                                    <span x-text="partner.city"></span> • 
                                    <span x-text="partner.contact_person"></span>
                                </div>
                            </div>
                        </div>
                        <div class="text-right">
                            <div class="text-sm font-medium text-gray-900" x-text="partner.pushCount + ' 次推送'"></div>
                            <div class="text-sm text-gray-500">
                                成功率: <span x-text="partner.successRate + '%'"></span>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            
            <!-- Empty State -->
            <div class="text-center py-12" x-show="!stats.topPartners || stats.topPartners.length === 0">
                <i class="fas fa-building text-4xl text-gray-400 mb-4"></i>
                <h4 class="text-lg font-medium text-gray-900 mb-2">暂无合作机构数据</h4>
                <p class="text-gray-500">还没有推送到任何合作机构</p>
            </div>
        </div>
    </div>

    <!-- Loading State -->
    <div class="text-center py-12" x-show="loading">
        <i class="fas fa-spinner fa-spin text-4xl text-gray-400 mb-4"></i>
        <p class="text-gray-500">正在加载统计数据...</p>
    </div>
</div>

<script>
    function pushStatsData() {
        return {
            loading: false,
            stats: {
                total: 0,
                success: 0,
                failed: 0,
                pending: 0,
                successRate: 0,
                byType: {},
                byStatus: {},
                dailyTrend: [],
                topPartners: []
            },
            
            dateRange: {
                startDate: '',
                endDate: ''
            },
            
            init() {
                this.setQuickRange('month');
                this.loadStats();
            },
            
            async loadStats() {
                this.loading = true;
                try {
                    const token = localStorage.getItem('token');
                    const params = new URLSearchParams();
                    
                    if (this.dateRange.startDate) {
                        params.append('start_date', this.dateRange.startDate);
                    }
                    if (this.dateRange.endDate) {
                        params.append('end_date', this.dateRange.endDate);
                    }
                    
                    const response = await fetch(`/api/v1/push/stats?${params.toString()}`, {
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            this.stats = {
                                total: data.data.total || 0,
                                success: data.data.success || 0,
                                failed: data.data.failed || 0,
                                pending: data.data.pending || 0,
                                successRate: data.data.success_rate || 0,
                                byType: data.data.by_type || {},
                                byStatus: data.data.by_status || {},
                                dailyTrend: data.data.daily_trend || [],
                                topPartners: data.data.top_partners || []
                            };
                        }
                    }
                } catch (error) {
                    console.error('Failed to load push stats:', error);
                    showToast('加载统计数据失败', 'error');
                } finally {
                    this.loading = false;
                }
            },
            
            refreshStats() {
                this.loadStats();
            },
            
            setQuickRange(range) {
                const today = new Date();
                const formatDate = (date) => date.toISOString().split('T')[0];
                
                switch (range) {
                    case 'today':
                        this.dateRange.startDate = formatDate(today);
                        this.dateRange.endDate = formatDate(today);
                        break;
                    case 'week':
                        const weekStart = new Date(today);
                        weekStart.setDate(today.getDate() - today.getDay());
                        this.dateRange.startDate = formatDate(weekStart);
                        this.dateRange.endDate = formatDate(today);
                        break;
                    case 'month':
                        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
                        this.dateRange.startDate = formatDate(monthStart);
                        this.dateRange.endDate = formatDate(today);
                        break;
                }
                
                this.loadStats();
            },
            
            isQuickRangeActive(range) {
                const today = new Date();
                const formatDate = (date) => date.toISOString().split('T')[0];
                
                switch (range) {
                    case 'today':
                        return this.dateRange.startDate === formatDate(today) && 
                               this.dateRange.endDate === formatDate(today);
                    case 'week':
                        const weekStart = new Date(today);
                        weekStart.setDate(today.getDate() - today.getDay());
                        return this.dateRange.startDate === formatDate(weekStart) && 
                               this.dateRange.endDate === formatDate(today);
                    case 'month':
                        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
                        return this.dateRange.startDate === formatDate(monthStart) && 
                               this.dateRange.endDate === formatDate(today);
                    default:
                        return false;
                }
            },
            
            getMaxDailyCount() {
                if (!this.stats.dailyTrend || this.stats.dailyTrend.length === 0) {
                    return 1;
                }
                return Math.max(...this.stats.dailyTrend.map(day => day.total));
            },
            
            getBarHeight(count, maxCount) {
                if (maxCount === 0) return 0;
                const maxHeight = 160; // 最大高度
                return Math.max(2, (count / maxCount) * maxHeight); // 最小高度2px
            },
            
            formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return (date.getMonth() + 1) + '/' + date.getDate();
            }
        }
    }
</script>
{{end}}